package com.bt.mes.brm.provider.service;

import static com.bt.mes.common.bean.def.GenericDef.ACTION_FLG_ADD;
import static com.bt.mes.common.bean.def.GenericDef.ACTION_FLG_DELETE;
import static com.bt.mes.common.bean.def.GenericDef.ACTION_FLG_INQUIRE;
import static com.bt.mes.common.bean.def.GenericDef.ACTION_FLG_LIST_BY_PATH;
import static com.bt.mes.common.bean.def.GenericDef.ACTION_FLG_LIST_WHOLE;
import static com.bt.mes.common.bean.def.GenericDef.ACTION_FLG_QUERY;
import static com.bt.mes.common.bean.def.GenericDef.ACTION_FLG_SEARCH;
import static com.bt.mes.common.bean.def.GenericDef.ACTION_FLG_UPDATE;
import static com.bt.mes.common.bean.def.GenericDef.E_XPBISOPE_BIS_PATH_NOT_FOUND;
import static com.bt.mes.common.bean.def.GenericDef.E_XPBISOPE_NOT_FOUND_OPE;
import static com.bt.mes.common.bean.def.GenericDef.E_XPBISOPE_OPE_ALREADY_EXIST;
import static com.bt.mes.common.bean.def.GenericDef.PATH_FRST_OPE;
import static com.bt.mes.common.bean.def.GenericDef.RETURN_CODE_OK;
import static com.bt.mes.common.bean.def.GenericDef.RETURN_CODE_UNKNOWN;
import static com.bt.mes.common.bean.def.GenericDef.RETURN_MESG_OK;
import static com.bt.mes.common.bean.def.GenericDef._SPACE;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.bt.mes.brm.api.service.IXpbisopeService;
import com.bt.mes.brm.provider.tx.Xpbisope.XpbisopeI;
import com.bt.mes.brm.provider.tx.Xpbisope.XpbisopeIA;
import com.bt.mes.brm.provider.tx.Xpbisope.XpbisopeIB;
import com.bt.mes.brm.provider.tx.Xpbisope.XpbisopeO;
import com.bt.mes.brm.provider.tx.Xpbisope.XpbisopeOA;
import com.bt.mes.common.dao.IBisDataDao;
import com.bt.mes.common.dao.IBisOpeDao;
import com.bt.mes.common.dao.IBisPathDao;
import com.bt.mes.common.util.JacksonUtil;
import com.bt.mes.common.util.Util;
import com.bt.table.ppt.Bis_data;
import com.bt.table.ppt.Bis_ope;
import com.bt.table.ppt.Bis_opeId;
import com.bt.table.ppt.Bis_path;

@Service("xpbisopeService")
public class XpbisopeService implements IXpbisopeService {
	private Logger logger = Logger.getLogger(XpbisopeService.class);
	@Autowired
	private XpbisopeI inTrx;

	@Autowired
	private XpbisopeO outTrx;

	@Autowired
	private IBisPathDao bisPathDao;

	@Autowired
	private IBisOpeDao bisOpeDao;

	@Autowired
	private IBisDataDao bisDataDao;

	public String subMainProc(String strInMsg) {
		logger.info("InTrx is " + strInMsg);
		Session session = bisOpeDao.getCrSession();
		String strOutTrx = null;
		try {
			outTrx.setTrx_id("XPBISOPE");
			outTrx.setType_id("O");
			inTrx = JacksonUtil.fromJson(strInMsg, XpbisopeI.class);
			char action_flg = inTrx.getAction_flg().charAt(0);
			switch (action_flg) {
			case ACTION_FLG_QUERY:
				queryByCondition();
				break;
			case ACTION_FLG_ADD:
				addFnc();
				break;
			case ACTION_FLG_UPDATE:
				updateFnc();
				break;
			case ACTION_FLG_DELETE:
				deleteFnc();
				break;
			case ACTION_FLG_LIST_WHOLE:
				listAllFnc();
				break;
			case ACTION_FLG_LIST_BY_PATH:
				findOpeByPATH();
				break;
			case ACTION_FLG_INQUIRE:
				findOpeByFabUsr();
				break;
			case ACTION_FLG_SEARCH:
				findOpeByFabUsr();
				break;
			default:
				errActionFnc();
			}
			if (RETURN_CODE_OK.equals(outTrx.getRtn_code())) {
				session.flush();
			} else {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		} catch (Exception ex) {
			logger.error(Util.stackTraceToString(ex));
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			outTrx.setRtn_mesg(ex.getCause().toString());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		} finally {
			strOutTrx = JacksonUtil.toJSONStr(outTrx);
			logger.info(strOutTrx);
		}
		return strOutTrx;
	}

	/**
	 * 根据厂别和用户，筛选出可以操作的站点。
	 * 
	 * @return
	 */
	private void findOpeByFabUsr() {
		String user_id;
		String opeIds = "", sql = "";
		int i = 0;
		XpbisopeIB iaryB = inTrx.getIaryB().get(0);
		List<XpbisopeOA> oaryList = new ArrayList<XpbisopeOA>();
		List<Bis_ope> bisOpeList = new ArrayList<Bis_ope>();
		List<Bis_data> dataList = new ArrayList<Bis_data>();
		user_id = iaryB.getUser_id();
		String admin_sql = " FROM Bis_data where data_cate = 'UFUG'AND DATA_EXT = '" + user_id
				+ "' AND EXT_1 = 'ADMIN' AND EXT_3='Y' ";
		List<Bis_data> UFUG_list = bisDataDao.find(admin_sql);
		if (UFUG_list.size() == 1) {
			String hql = "FROM Bis_ope order by convert(pep_lvl,UNSIGNED) ";
			bisOpeList = bisOpeDao.find(hql);
		} else {

			sql = " SELECT * FROM BIS_DATA A INNER JOIN BIS_DATA B ON A.EXT_1 = B.EXT_1 "
					+ " WHERE A.DATA_CATE IN ('UROP') AND A.DATA_EXT = '" + user_id + "'";
			dataList = bisDataDao.findBySQL(sql, Bis_data.class);
			for (i = 0; i < dataList.size(); i++) {
				Bis_data bis_data = dataList.get(i);
				if (i == 0) {
					opeIds = "'" + bis_data.getExt_1() + "'";
				} else {
					opeIds += ",'" + bis_data.getExt_1() + "'";
				}
			}
			if (!opeIds.equals(_SPACE)) {
				String opeSql = "FROM Bis_ope where ope_id in(" + opeIds + ")and ope_ver='00000'"
						+ "order by convert(pep_lvl,UNSIGNED)";
				bisOpeList = bisOpeDao.find(opeSql);
			}
		}
		for (Bis_ope bis_ope : bisOpeList) {
			XpbisopeOA oary = new XpbisopeOA();
			oary.setOpe_id(bis_ope.getId().getOpe_id());
			oary.setOpe_ver(bis_ope.getId().getOpe_ver());
			oary.setOpe_dsc(bis_ope.getOpe_dsc());
			oary.setProc_id(bis_ope.getProc_id());
			oary.setToolg_id(bis_ope.getToolg_id());
			oary.setPep_lvl(bis_ope.getPep_lvl());
			oary.setSwh_seq_id(bis_ope.getSwh_seq_id());
			oary.setSwh_cnt(bis_ope.getSwh_cnt());
			oary.setYield_chk_flg(bis_ope.getYield_chk_flg());
			oary.setHand_over_flg(bis_ope.getHand_over_flg());
			oary.setDept_id_data_id_fk(bis_ope.getDept_id_data_id_fk());
			oary.setStd_ope_time(bis_ope.getStd_ope_time());
			oary.setUp_load_id(bis_ope.getUp_load_id());
			oary.setDn_load_id(bis_ope.getDn_load_id());
			oaryList.add(oary);
		}
		/**
		 * 2100界面拆并箱时，需要PACK/WH两个站点。
		 */
		if (inTrx.getAction_flg().equals("S")) {
			if (UFUG_list.size() == 1) {
				XpbisopeOA oary = new XpbisopeOA();
				oary.setOpe_id("PACK");
				oary.setOpe_dsc("包装");
				oary.setOpe_ver("00000");
				oaryList.add(oary);
				XpbisopeOA oary2 = new XpbisopeOA();
				oary2.setOpe_id("WH");
				oary2.setOpe_dsc("成品");
				oary2.setOpe_ver("00000");
				oaryList.add(oary2);
			} else {
				for (i = 0; i < dataList.size(); i++) {
					XpbisopeOA oary = new XpbisopeOA();
					Bis_data bis_data = dataList.get(i);
					if (bis_data.getExt_1().equals("PACK")) {
						oary.setOpe_id("PACK");
						oary.setOpe_dsc("包装");
						oary.setOpe_ver("00000");
						oaryList.add(oary);
					} else if (bis_data.getExt_1().equals("WH")) {
						oary.setOpe_id("WH");
						oary.setOpe_dsc("成品");
						oary.setOpe_ver("00000");
						oaryList.add(oary);
					}
				}
			}

		}
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	private void addFnc() {

		XpbisopeIA iary = inTrx.getIary().get(0);
		String ope_id = iary.getOpe_id();
		String ope_ver = iary.getOpe_ver();
		Bis_opeId id = new Bis_opeId();
		id.setOpe_id(ope_id);
		id.setOpe_ver(ope_ver);
		Bis_ope queryBisOpe = bisOpeDao.get(id);
		if (queryBisOpe != null) {
			outTrx.setRtn_code(E_XPBISOPE_OPE_ALREADY_EXIST + "");
			outTrx.setRtn_code("ope_id Already Exist");
			return;
		}
		Bis_ope bisOpe = new Bis_ope();
		bisOpe.setId(id);
		bisOpe.setOpe_dsc(iary.getOpe_dsc());
		bisOpe.setProc_id(iary.getProc_id());
		bisOpe.setToolg_id(iary.getToolg_id());
		bisOpe.setPep_lvl(iary.getPep_lvl());
		bisOpe.setSwh_seq_id(bisOpe.getSwh_seq_id());
		bisOpe.setSwh_cnt(bisOpe.getSwh_cnt());
		bisOpe.setYield_chk_flg(iary.getYield_chk_flg());
		bisOpe.setHand_over_flg(iary.getHand_over_flg());
		bisOpe.setDept_id_data_id_fk(iary.getDept_id_data_id_fk());
		bisOpe.setStd_ope_time(iary.getStd_ope_time());
		bisOpe.setUp_load_id(iary.getUp_load_id());
		bisOpe.setDn_load_id(iary.getDn_load_id());
		bisOpeDao.save(bisOpe);
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);

	}

	public void updateFnc() {
		XpbisopeIA iary = inTrx.getIary().get(0);
		String ope_id = iary.getOpe_id();
		String ope_ver = iary.getOpe_ver();
		Bis_opeId id = new Bis_opeId();
		id.setOpe_id(ope_id);
		id.setOpe_ver(ope_ver);
		Bis_ope bisOpe = bisOpeDao.get(id);
		if (bisOpe == null) {
			outTrx.setRtn_code(E_XPBISOPE_NOT_FOUND_OPE + "");
			outTrx.setRtn_code("not found ope");
			return;
		}
		if (iary.getOpe_dsc() != null) {
			bisOpe.setOpe_dsc(iary.getOpe_dsc());
		}
		if (iary.getProc_id() != null) {
			bisOpe.setProc_id(iary.getProc_id());
		}
		if (iary.getToolg_id() != null) {
			bisOpe.setToolg_id(iary.getToolg_id());
		}
		if (iary.getPep_lvl() != null) {
			bisOpe.setPep_lvl(iary.getPep_lvl());
		}
		if (bisOpe.getSwh_seq_id() != null) {
			bisOpe.setSwh_seq_id(bisOpe.getSwh_seq_id());
		}
		if (bisOpe.getSwh_cnt() != null) {
			bisOpe.setSwh_cnt(bisOpe.getSwh_cnt());
		}
		if (iary.getYield_chk_flg() != null) {
			bisOpe.setYield_chk_flg(iary.getYield_chk_flg());
		}
		if (iary.getHand_over_flg() != null) {
			bisOpe.setHand_over_flg(iary.getHand_over_flg());
		}
		if (iary.getDept_id_data_id_fk() != null) {
			bisOpe.setDept_id_data_id_fk(iary.getDept_id_data_id_fk());
		}
		if (iary.getStd_ope_time() != null) {
			bisOpe.setStd_ope_time(iary.getStd_ope_time());
		}
		if (iary.getUp_load_id() != null) {
			bisOpe.setUp_load_id(iary.getUp_load_id());
		}
		if (iary.getDn_load_id() != null) {
			bisOpe.setDn_load_id(iary.getDn_load_id());
		}
		bisOpeDao.update(bisOpe);
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void deleteFnc() {
		XpbisopeIA iary = inTrx.getIary().get(0);
		String ope_id = iary.getOpe_id();
		String ope_ver = iary.getOpe_ver();
		Bis_opeId id = new Bis_opeId();
		id.setOpe_id(ope_id);
		id.setOpe_ver(ope_ver);
		Bis_ope bisOpe = bisOpeDao.get(id);
		if (bisOpe == null) {
			outTrx.setRtn_code(E_XPBISOPE_NOT_FOUND_OPE + "");
			outTrx.setRtn_code("not found ope");
			return;
		}
		bisOpeDao.delete(bisOpe);
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		return;
	}

	public void queryByCondition() {
		XpbisopeIA iary = inTrx.getIary().get(0);
		/***
		 * 支持 按ope_id,ope_ver 模糊查询
		 ***/
		String ope_id = iary.getOpe_id();
		String ope_ver = iary.getOpe_ver();
		String proc_id = iary.getProc_id();
		String hql = "FROM Bis_ope where 1=1 ";
		if (ope_id != null) {
			if (ope_id.indexOf('*') == -1) {
				hql = hql + " and ope_id='" + ope_id + "'";
			} else {
				hql = hql + " and ope_id like '" + ope_id.replace('*', '%') + "'";
			}
		}
		if (ope_ver != null) {
			if (ope_ver.indexOf('*') == -1) {
				hql = hql + " and ope_ver='" + ope_ver + "'";
			} else {
				hql = hql + " and ope_ver like '" + ope_ver.replace('*', '%') + "'";
			}
		}
		if (proc_id != null) {
			hql = hql + " and proc_id in (SELECT data_ext FROM Bis_data where data_cate = 'PRST' " + " and ext_4 =  '"
					+ proc_id + "')";
		}
		hql = hql + " order by convert(pep_lvl,UNSIGNED)";
		List<Bis_ope> bisOpeList = bisOpeDao.find(hql);
		List<XpbisopeOA> oaryList = new ArrayList<XpbisopeOA>();
		for (Bis_ope bis_ope : bisOpeList) {
			XpbisopeOA oary = new XpbisopeOA();
			oary.setOpe_id(bis_ope.getId().getOpe_id());
			oary.setOpe_ver(bis_ope.getId().getOpe_ver());
			oary.setOpe_dsc(bis_ope.getOpe_dsc());
			oary.setProc_id(bis_ope.getProc_id());
			oary.setToolg_id(bis_ope.getToolg_id());
			oary.setPep_lvl(bis_ope.getPep_lvl());
			oary.setSwh_seq_id(bis_ope.getSwh_seq_id());
			oary.setSwh_cnt(bis_ope.getSwh_cnt());
			oary.setYield_chk_flg(bis_ope.getYield_chk_flg());
			oary.setHand_over_flg(bis_ope.getHand_over_flg());
			oary.setDept_id_data_id_fk(bis_ope.getDept_id_data_id_fk());
			oary.setStd_ope_time(bis_ope.getStd_ope_time());
			oary.setUp_load_id(bis_ope.getUp_load_id());
			oary.setDn_load_id(bis_ope.getDn_load_id());
			oaryList.add(oary);
		}
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		return;
	}

	public void listAllFnc() {
		List<XpbisopeOA> oaryList = new ArrayList<XpbisopeOA>();
		String hql = "FROM Bis_ope where 1=1 order by convert(pep_lvl,UNSIGNED) ";
		List<Bis_ope> bisOpeList = bisOpeDao.find(hql);
		for (Bis_ope bis_ope : bisOpeList) {
			XpbisopeOA oary = new XpbisopeOA();
			oary.setOpe_id(bis_ope.getId().getOpe_id());
			oary.setOpe_ver(bis_ope.getId().getOpe_ver());
			oary.setOpe_dsc(bis_ope.getOpe_dsc());
			oary.setProc_id(bis_ope.getProc_id());
			oaryList.add(oary);
		}
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void errActionFnc() {
		outTrx.setRtn_code("0000009");
		outTrx.setRtn_mesg("Invalid Action_flg");
	}

	/**
	 * 按照先后顺序筛选站点
	 * 
	 * @return
	 */
	public void findOpeByPATH() {

		String pv_ope_no = "";
		String sql = "FROM Bis_path where id.path_id_fk='" + inTrx.getPath_id_fk() + "' and " + "id.path_ver_fk='"
				+ inTrx.getPath_ver_fk() + "'";
		List<Bis_path> bis_pathList = new ArrayList<Bis_path>();
		bis_pathList = bisPathDao.find(sql);
		if (bis_pathList.isEmpty()) {
			outTrx.setRtn_code(E_XPBISOPE_BIS_PATH_NOT_FOUND + "");
			outTrx.setRtn_mesg("工艺路线：[" + inTrx.getPath_id_fk() + "]未找到！");
			return;
		}
		List<XpbisopeOA> oaryList = new ArrayList<XpbisopeOA>();
		for (Bis_path cr_ope_no : bis_pathList) {
			Bis_opeId bis_opeId = new Bis_opeId();
			bis_opeId.setOpe_id(cr_ope_no.getCr_ope_id_fk());
			bis_opeId.setOpe_ver(cr_ope_no.getCr_ope_ver_fk());
			Bis_ope bis_ope = bisOpeDao.get(bis_opeId);
			if (bis_ope == null) {
				outTrx.setRtn_code(E_XPBISOPE_NOT_FOUND_OPE + "");
				outTrx.setRtn_mesg(
						"工艺路线：[" + inTrx.getPath_id_fk() + "]中的站点：[" + cr_ope_no.getCr_ope_id_fk() + "]，信息未找到！");
				return;
			}
			if (cr_ope_no.getPv_ope_no().equals(PATH_FRST_OPE)) {
				pv_ope_no = cr_ope_no.getId().getCr_ope_no();
				XpbisopeOA oary = new XpbisopeOA();
				oary.setOpe_no(pv_ope_no);
				oary.setOpe_id(bis_ope.getId().getOpe_id());
				oary.setOpe_ver(bis_ope.getId().getOpe_ver());
				oary.setOpe_dsc(bis_ope.getOpe_dsc());
				oary.setProc_id(bis_ope.getProc_id());
				oary.setToolg_id(bis_ope.getToolg_id());
				oaryList.add(oary);
				break;
			}
		}
		for (Bis_path cr_ope_no : bis_pathList) {
			if (cr_ope_no.getPv_ope_no().equals(PATH_FRST_OPE)) {
				continue;
			} else {
				for (int i = 0; i < bis_pathList.size(); i++) {
					Bis_path ope_no = bis_pathList.get(i);
					if (ope_no.getPv_ope_no().trim().equals(pv_ope_no.trim())) {
						Bis_opeId bis_opeId = new Bis_opeId();
						bis_opeId.setOpe_id(ope_no.getCr_ope_id_fk());
						bis_opeId.setOpe_ver(ope_no.getCr_ope_ver_fk());
						Bis_ope bis_ope = bisOpeDao.get(bis_opeId);
						if (bis_ope == null) {
							outTrx.setRtn_code(E_XPBISOPE_NOT_FOUND_OPE + "");
							outTrx.setRtn_mesg("工艺路线：[" + inTrx.getPath_id_fk() + "]中的站点：["
									+ cr_ope_no.getCr_ope_id_fk() + "]，信息未找到！");
							return;
						}
						pv_ope_no = ope_no.getId().getCr_ope_no();
						XpbisopeOA oary = new XpbisopeOA();
						oary.setOpe_no(pv_ope_no);
						oary.setOpe_id(bis_ope.getId().getOpe_id());
						oary.setOpe_ver(bis_ope.getId().getOpe_ver());
						oary.setProc_id(bis_ope.getProc_id());
						oary.setOpe_dsc(bis_ope.getOpe_dsc());
						oary.setToolg_id(bis_ope.getToolg_id());
						oaryList.add(oary);
						break;
					}
				}

			}

		}
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		return;

	}

}
